/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commands;

import general.IOption;

import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.Map.Entry;

/**
 *
 * eCOM - Adopte un Presta - Mars-Avril 2013
 * @author Kheira, Jef, William, Tuan-Long
 */
public abstract class CommandAbstractAction extends CommandAbstract {
    private PrintStream out;
    private PrintStream err;

    @Override
    protected final void execute(PrintStream out, PrintStream err) 
    {
        this.out = out;
	this.err = err;
        
	if (this.values.size() > 0) 
        {
            Entry<IOption, String> firstOptionEntry = this.values.entrySet().iterator().next();
            String firstOptionValue = firstOptionEntry.getValue();
            IOption firstOption = firstOptionEntry.getKey();
            String optionName = firstOption.getName();		
            String actionName = optionName + "Action";
            
            
            dataArguments.addFirst(firstOptionValue);
			
            Method actionMethod = null;		
            try 
            {
                actionMethod = this.getClass().getMethod(actionName);
            } 
            catch (Exception ex) 
            {
                err.println("No Action named : '"+actionName+"'");
            }

            if (actionMethod != null) 
            {
                try 
                {
                    actionMethod.invoke(this);
		} 
                catch (Exception ex) 
                {
                    err.println("Cannot execute action named : '" + actionName + "'");
		}
            }
        } 
        else 
        {
            defaultAction();
	}
    }
    
        protected abstract void defaultAction();

	protected final PrintStream getOut() {
		return out;
	}
    
	protected final PrintStream getErr() {
		return err;
	}


}
